import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  StatusBar,
  TouchableOpacity,
  ActivityIndicator,
  Modal,
  TextInput,
  KeyboardAvoidingView,
  Platform,
  Alert,
  useColorScheme,
  NativeModules,
  NativeEventEmitter,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage';

const primary = '#1A73E8';
const backgroundStart = '#F5F7FA';
// const { WeChatHelper } = NativeModules;

export default function LoginScreen() {
  const isDark = useColorScheme() === 'dark';

  const [installed, setInstalled] = useState(false);
  const [loading, setLoading] = useState(false);
  const [configVisible, setConfigVisible] = useState(false);
  const [baseUrl, setBaseUrl] = useState('');
  const [port, setPort] = useState('');
  const [apiPrefix, setApiPrefix] = useState('');

  // useEffect(() => {
  //   // —— 判断微信是否安装 ——
  //   WeChatHelper.isWeChatInstalled()
  //     .then(setInstalled)
  //     .catch((e: any) => console.error(e));

  //   // —— 监听原生发过来的授权结果广播 ——
  //   const emitter = new NativeEventEmitter(WeChatHelper);
  //   const sub = emitter.addListener(
  //     'WeChat_AuthResponse',
  //     ({ errCode, code, state }) => {
  //       if (errCode === 0 && code) {
  //         Alert.alert('登录成功', `code = ${code}`);
  //         // TODO: 用 code 调后端接口换 token，保存后导航
  //       } else {
  //         Alert.alert('登录失败', `errCode=${errCode}`);
  //       }
  //       setLoading(false);
  //     },
  //   );
  //   return () => sub.remove();
  // }, []);

  // —— DEBUG: 捕获所有未处理的 JS 异常 ——
  useEffect(() => {
    const oldHandler =
      ErrorUtils.getGlobalHandler && ErrorUtils.getGlobalHandler();
    ErrorUtils.setGlobalHandler((error, isFatal) => {
      console.error('捕获到全局异常:', error, 'fatal?', isFatal);
      oldHandler && oldHandler(error, isFatal);
    });
  }, []);

  // 通过 sendAuthRequest 返回的 Promise 拿到 code 并处理登录逻辑
  const onWeChatLogin = useCallback(async () => {
    // if (loading) return;
    // setLoading(true);
    // // 直接触发原生登录，结果会通过 WeChat_AuthResponse 事件回调
    // const started = await WeChatHelper.login();
    // if (!started) {
    //   Alert.alert('登录失败', '启动微信登录请求失败');
    //   setLoading(false);
    // }
  }, [loading]);

  const saveConfig = async () => {
    if (!baseUrl || !port) {
      Alert.alert('提示', '请填写完整信息');
      return;
    }
    await AsyncStorage.multiSet([
      ['BASE_URL', baseUrl],
      ['PORT', port],
      ['API_PREFIX', apiPrefix],
    ]);
    setConfigVisible(false);
    Alert.alert('提示', '配置已保存，本次启动立即生效');
  };

  return (
    <LinearGradient
      style={styles.flex}
      colors={[backgroundStart, '#FFF']}
      start={{ x: 0, y: 0 }}
      end={{ x: 0, y: 1 }}
    >
      <StatusBar barStyle={isDark ? 'light-content' : 'dark-content'} />

      {/* 顶部右侧设置按钮 */}
      <TouchableOpacity
        style={styles.settingBtn}
        onPress={() => setConfigVisible(true)}
      >
        <Icon name="settings" size={24} color="#999" />
      </TouchableOpacity>

      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        style={styles.flex}
      >
        <View style={styles.container}>
          {/* Logo & 标题 */}
          <Icon name="store" size={80} color={primary} />
          <Text style={styles.title}>欢迎登录</Text>

          {/* 占位：推登录按钮到底部一些 */}
          <View style={styles.spacer} />

          {/* 微信登录按钮 */}
          <TouchableOpacity
            disabled={!installed || loading}
            style={[
              styles.button,
              { backgroundColor: installed ? primary : '#ccc' },
            ]}
            onPress={onWeChatLogin}
          >
            {loading ? (
              <ActivityIndicator color="#fff" />
            ) : (
              <Icon name="wechat" size={20} color="#fff" />
            )}
            <Text style={styles.btnText}>
              {installed ? '微信一键登录' : '请先安装微信'}
            </Text>
          </TouchableOpacity>

          {/* 底部协议 */}
          <Text style={styles.protocol}>
            登录即表示您同意
            <Text style={styles.link}>《用户协议》</Text>和
            <Text style={styles.link}>《隐私政策》</Text>
          </Text>
        </View>
      </KeyboardAvoidingView>

      {/* 配置弹窗 */}
      <Modal visible={configVisible} transparent animationType="fade">
        <View style={styles.modalMask}>
          <View style={styles.modal}>
            <Text style={styles.modalTitle}>应用配置</Text>
            <TextInput
              placeholder="请求地址"
              style={styles.input}
              value={baseUrl}
              onChangeText={setBaseUrl}
            />
            <TextInput
              placeholder="端口号"
              style={styles.input}
              value={port}
              onChangeText={setPort}
              keyboardType="numeric"
            />
            <TextInput
              placeholder="API 前缀"
              style={styles.input}
              value={apiPrefix}
              onChangeText={setApiPrefix}
            />
            <View style={styles.modalActions}>
              <TouchableOpacity onPress={() => setConfigVisible(false)}>
                <Text style={styles.cancel}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={saveConfig}>
                <Text style={styles.save}>保存</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </LinearGradient>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1 },
  container: {
    flex: 1,
    paddingHorizontal: 24,
    alignItems: 'center',
    justifyContent: 'center',
  },
  settingBtn: { position: 'absolute', top: 16, right: 16, zIndex: 10 },
  title: {
    fontSize: 28,
    fontWeight: '700',
    color: primary,
    marginTop: 16,
  },
  spacer: { height: 200 },
  button: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 14,
    paddingHorizontal: 32,
    borderRadius: 12,
    elevation: 4,
    shadowColor: '#0004',
  },
  btnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
    marginLeft: 8,
  },
  protocol: {
    fontSize: 12,
    color: '#666',
    textAlign: 'center',
    marginTop: 40,
  },
  link: { color: primary },
  /* ---- Modal ---- */
  modalMask: {
    flex: 1,
    backgroundColor: '#0005',
    alignItems: 'center',
    justifyContent: 'center',
  },
  modal: {
    width: '80%',
    backgroundColor: '#fff',
    padding: 20,
    borderRadius: 16,
  },
  modalTitle: { fontSize: 18, fontWeight: '700', marginBottom: 16 },
  input: {
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: '#ccc',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
    marginBottom: 14,
  },
  modalActions: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginTop: 6,
  },
  cancel: { fontSize: 15, color: '#666', marginRight: 24 },
  save: { fontSize: 15, color: primary, fontWeight: '700' },
});
